import ipfsapi as ia
import os
import shutil
from common.randomtools import gen_random_int_str
from common.args import TmpIPFSFolder
from common.path import file_path_join
from common import print_exception
from common import print_msg

# a class to pack up all function about ipfs



# TEMPORARY_FILEPATH=os.getcwd()
TEMPORARY_FILEPATH= file_path_join(os.getcwd(),TmpIPFSFolder)

class ipfs_tool():

    def __init__(self,ipfshost='127.0.0.1',ipfsport=5001):
        self.host=ipfshost
        self.port=ipfsport
        self._api=None


    def connection(self):
        try:
            self._api=ia.connect(self.host,self.port)
            print_msg("Connection success")
        except ia.exceptions.Error as ce:
            print_exception(ce)
            raise ce



    # upload file to ipfs
    # input：filepath and isdirectory
    # return a dict : {"Name": filename , "Hash": file hash code , "Size": file size}



    def uploadfile(self,filepath,isdirectory=False):
        try:
            d=self._api.add(filepath,recursive=isdirectory)
            print_msg("upload success")
            return d
        except ia.exceptions.Error as ce:
            print_exception(ce)
            raise ce

            

    #
    # get file from ipfs and move the file to a certain path
    # Input: hashcode
    # file are placed in the current working directory 
    # the name of this file is its hash code 
    #

    def getfile(self,hashcode,outputpath=None):
        #
        # It is better to make outputpath equal to a static data
        #
        try:
            self._api.get(hashcode)
            print_msg("the file is in the working directory")
            # move the file or directory under a certain directory.
            if(outputpath!=None and os.path.exists(outputpath)):
                p=os.path.join(os.getcwd(),hashcode)
                shutil.move(p,outputpath)
            else:
                print_msg('outpath is not exist')
        except ia.exceptions.Error as ce:
            print_exception(ce)
            raise ce



    #Description: get content of a file and upload this content
    #
    # # Input: content
    #
    #  Output:  a dict : {"Name": filename , "Hash": file hash code , "Size": file size}
    #

    def uploadincontent(self,content):
        # generate random file name
        filename=gen_random_int_str()
        p=os.path.join(TEMPORARY_FILEPATH,filename)
        while(os.path.exists(p)):
            filename=gen_random_int_str()
            p=os.path.join(TEMPORARY_FILEPATH,filename)

        with open(p,'wb') as f:
            f.write(content)
        # print(p) # ?????
        try:
            d=self.uploadfile(p)
            os.remove(p)
            return d
        except ia.exceptions.Error as ce:
            print_exception(ce)
            raise ce

    

    #Description: get content of certain file
    #
    #input: hashcode
    #
    #Output:content(bytes)

    def catfilecontent(self,hashcode):

        return self._api.cat(hashcode)